#include <QApplication>
#include <QMainWindow>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTableWidget>
#include <QGroupBox>
#include <QLabel>
#include <QPushButton>
#include <QProgressBar>
#include <QHeaderView>
#include <QTimer>
#include <QMessageBox>
#include <QProcess>
#include <QToolBar>
#include <QAction>
#include <QIcon>
#include <QMenuBar>
#include <QMenu>
#include <QTableWidgetItem>
#include <QColor>
#include <QInputDialog>

#include "taskmanager.h"
#include "systemmonitor.h"

class TaskManagerWindow : public QMainWindow {
    Q_OBJECT

public:
    TaskManagerWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
        setupUI();
        setupTimers();
        updateProcesses();
        updateSystemInfo();
    }

private slots:
    void updateProcesses() {
        m_processManager.update_processes(m_currentFilter);
        const auto& processes = m_processManager.get_processes();
        
        // 保存当前选中的行
        int selectedRow = -1;
        if (m_processTable->selectionModel()->hasSelection()) {
            selectedRow = m_processTable->currentRow();
        }
        
        m_processTable->setRowCount(processes.size());
        for (size_t i = 0; i < processes.size(); ++i) {
            const auto& proc = processes[i];
            
            // 进程名称
            QTableWidgetItem *nameItem = new QTableWidgetItem(QString::fromStdString(proc.name));
            m_processTable->setItem(i, 0, nameItem);
            
            // PID
            QTableWidgetItem *pidItem = new QTableWidgetItem(QString::number(proc.pid));
            m_processTable->setItem(i, 1, pidItem);
            
            // 状态
            QTableWidgetItem *statusItem = new QTableWidgetItem(QString::fromStdString(proc.status));
            m_processTable->setItem(i, 2, statusItem);
            
            // 用户
            QTableWidgetItem *userItem = new QTableWidgetItem(QString::fromStdString(proc.user));
            m_processTable->setItem(i, 3, userItem);
            
            // CPU%
            QTableWidgetItem *cpuItem = new QTableWidgetItem(QString::number(proc.cpu_percent, 'f', 1));
            if (proc.cpu_percent > 50.0) {
                cpuItem->setForeground(QColor("red"));
            }
            m_processTable->setItem(i, 4, cpuItem);
            
            // 内存%
            QTableWidgetItem *memPercentItem = new QTableWidgetItem(QString::number(proc.memory_percent, 'f', 1));
            if (proc.memory_percent > 50.0) {
                memPercentItem->setForeground(QColor("red"));
            }
            m_processTable->setItem(i, 5, memPercentItem);
            
            // 内存
            QTableWidgetItem *memItem = new QTableWidgetItem(QString::number(proc.memory_rss / 1024.0 / 1024.0, 'f', 1) + " MB");
            m_processTable->setItem(i, 6, memItem);
            
            // 运行时间
            QTableWidgetItem *uptimeItem = new QTableWidgetItem(QString::fromStdString(proc.uptime));
            m_processTable->setItem(i, 7, uptimeItem);
            
            // 命令行
            QTableWidgetItem *cmdItem = new QTableWidgetItem(QString::fromStdString(proc.cmdline));
            m_processTable->setItem(i, 8, cmdItem);
            
            // 优先级
            QTableWidgetItem *niceItem = new QTableWidgetItem(QString::number(proc.nice));
            m_processTable->setItem(i, 9, niceItem);
        }
        
        // 恢复选中行
        if (selectedRow >= 0 && selectedRow < m_processTable->rowCount()) {
            m_processTable->selectRow(selectedRow);
        }
        
        m_processTable->resizeColumnsToContents();
    }
    
    void updateSystemInfo() {
        SystemInfo sysInfo = m_systemMonitor.get_system_info();
        
        // 更新CPU信息
        m_cpuProgress->setValue(static_cast<int>(sysInfo.cpu_percent));
        m_cpuLabel->setText(QString("CPU: %1%").arg(sysInfo.cpu_percent, 0, 'f', 1));
        
        // 更新内存信息
        m_memoryProgress->setValue(static_cast<int>(sysInfo.memory_percent));
        m_memoryLabel->setText(QString("内存: %1% (%2 MB / %3 MB)")
                              .arg(sysInfo.memory_percent, 0, 'f', 1)
                              .arg(sysInfo.memory_used, 0, 'f', 0)
                              .arg(sysInfo.memory_total, 0, 'f', 0));
        
        // 更新磁盘信息
        m_diskProgress->setValue(static_cast<int>(sysInfo.disk_percent));
        m_diskLabel->setText(QString("磁盘: %1% (%2 MB / %3 MB)")
                            .arg(sysInfo.disk_percent, 0, 'f', 1)
                            .arg(sysInfo.disk_used, 0, 'f', 0)
                            .arg(sysInfo.disk_total, 0, 'f', 0));
    }
    
    void filterProcesses(const std::string& filter) {
        m_currentFilter = filter;
        updateProcesses();
    }
    
    void endProcess() {
        if (!m_processTable->selectionModel()->hasSelection()) {
            QMessageBox::warning(this, "警告", "请先选择一个进程");
            return;
        }
        
        int row = m_processTable->currentRow();
        QString name = m_processTable->item(row, 0)->text();
        int pid = m_processTable->item(row, 1)->text().toInt();
        
        int ret = QMessageBox::question(this, "确认", 
                                       QString("确定要结束进程 %1 (PID: %2) 吗？").arg(name).arg(pid));
        if (ret == QMessageBox::Yes) {
            if (m_processManager.terminate_process(pid)) {
                QMessageBox::information(this, "成功", "进程已结束");
                updateProcesses();
            } else {
                QMessageBox::warning(this, "失败", "无法结束进程");
            }
        }
    }
    
    void endProcessTree() {
        if (!m_processTable->selectionModel()->hasSelection()) {
            QMessageBox::warning(this, "警告", "请先选择一个进程");
            return;
        }
        
        int row = m_processTable->currentRow();
        QString name = m_processTable->item(row, 0)->text();
        int pid = m_processTable->item(row, 1)->text().toInt();
        
        int ret = QMessageBox::question(this, "确认", 
                                       QString("确定要结束进程树 %1 (PID: %2) 吗？").arg(name).arg(pid));
        if (ret == QMessageBox::Yes) {
            if (m_processManager.terminate_process_tree(pid)) {
                QMessageBox::information(this, "成功", "进程树已结束");
                updateProcesses();
            } else {
                QMessageBox::warning(this, "失败", "无法结束进程树");
            }
        }
    }
    
    void startProcess() {
        bool ok;
        QString text = QInputDialog::getText(this, "启动进程", "请输入要启动的命令:", QLineEdit::Normal, "", &ok);
        if (ok && !text.isEmpty()) {
            QStringList args = text.split(" ");
            QString program = args.first();
            args.removeFirst();
            
            QProcess::startDetached(program, args);
            updateProcesses();
        }
    }

private:
    void setupUI() {
        setWindowTitle("任务管理器");
        resize(1000, 700);
        
        // 创建菜单栏
        QMenuBar *menuBar = new QMenuBar(this);
        setMenuBar(menuBar);
        
        QMenu *fileMenu = menuBar->addMenu("文件(&F)");
        QAction *exitAction = fileMenu->addAction("退出(&X)");
        connect(exitAction, &QAction::triggered, this, &QMainWindow::close);
        
        QMenu *viewMenu = menuBar->addMenu("查看(&V)");
        QAction *updateOnceAction = viewMenu->addAction("刷新(&R)");
        updateOnceAction->setShortcut(QKeySequence("F5"));
        connect(updateOnceAction, &QAction::triggered, this, &TaskManagerWindow::updateProcesses);
        
        QMenu *helpMenu = menuBar->addMenu("帮助(&H)");
        QAction *aboutAction = helpMenu->addAction("关于(&A)");
        connect(aboutAction, &QAction::triggered, [this]() {
            QMessageBox::about(this, "关于", "Linux任务管理器\n基于Qt和C++开发");
        });
        
        // 创建工具栏
        QToolBar *toolBar = addToolBar("工具栏");
        QAction *updateAction = toolBar->addAction("刷新");
        updateAction->setShortcut(QKeySequence("F5"));
        connect(updateAction, &QAction::triggered, this, &TaskManagerWindow::updateProcesses);
        
        QAction *endProcessAction = toolBar->addAction("结束进程");
        connect(endProcessAction, &QAction::triggered, this, &TaskManagerWindow::endProcess);
        
        QAction *endProcessTreeAction = toolBar->addAction("结束进程树");
        connect(endProcessTreeAction, &QAction::triggered, this, &TaskManagerWindow::endProcessTree);
        
        QAction *startProcessAction = toolBar->addAction("启动进程");
        connect(startProcessAction, &QAction::triggered, this, &TaskManagerWindow::startProcess);
        
        // 创建标签页
        QTabWidget *tabWidget = new QTabWidget(this);
        setCentralWidget(tabWidget);
        
        // 进程标签页
        QWidget *processTab = createProcessTab();
        tabWidget->addTab(processTab, "进程");
        
        // 性能标签页
        QWidget *performanceTab = createPerformanceTab();
        tabWidget->addTab(performanceTab, "性能");
    }
    
    QWidget* createProcessTab() {
        QWidget *tab = new QWidget();
        QVBoxLayout *layout = new QVBoxLayout(tab);
        
        // 进程过滤按钮
        QHBoxLayout *filterLayout = new QHBoxLayout();
        QPushButton *allProcessesBtn = new QPushButton("所有进程");
        QPushButton *userProcessesBtn = new QPushButton("用户进程");
        QPushButton *systemProcessesBtn = new QPushButton("系统进程");
        QPushButton *servicesBtn = new QPushButton("后台服务");
        
        allProcessesBtn->setCheckable(true);
        userProcessesBtn->setCheckable(true);
        systemProcessesBtn->setCheckable(true);
        servicesBtn->setCheckable(true);
        
        allProcessesBtn->setChecked(true);
        
        connect(allProcessesBtn, &QPushButton::clicked, [this]() { filterProcesses("all"); });
        connect(userProcessesBtn, &QPushButton::clicked, [this]() { filterProcesses("user"); });
        connect(systemProcessesBtn, &QPushButton::clicked, [this]() { filterProcesses("system"); });
        connect(servicesBtn, &QPushButton::clicked, [this]() { filterProcesses("services"); });
        
        filterLayout->addWidget(allProcessesBtn);
        filterLayout->addWidget(userProcessesBtn);
        filterLayout->addWidget(systemProcessesBtn);
        filterLayout->addWidget(servicesBtn);
        filterLayout->addStretch();
        layout->addLayout(filterLayout);
        
        // 进程表格
        m_processTable = new QTableWidget();
        m_processTable->setColumnCount(10);
        m_processTable->setHorizontalHeaderLabels(QStringList() 
            << "映像名称" << "PID" << "状态" << "用户" << "CPU%" 
            << "内存%" << "内存" << "运行时间" << "命令行" << "优先级");
        m_processTable->setSelectionBehavior(QAbstractItemView::SelectRows);
        m_processTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
        m_processTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
        m_processTable->setSortingEnabled(true);
        layout->addWidget(m_processTable);
        
        return tab;
    }
    
    QWidget* createPerformanceTab() {
        QWidget *tab = new QWidget();
        QVBoxLayout *layout = new QVBoxLayout(tab);
        
        // CPU使用率
        QGroupBox *cpuGroup = new QGroupBox("CPU使用率");
        QVBoxLayout *cpuLayout = new QVBoxLayout(cpuGroup);
        m_cpuProgress = new QProgressBar();
        m_cpuProgress->setRange(0, 100);
        cpuLayout->addWidget(m_cpuProgress);
        m_cpuLabel = new QLabel("CPU: 0%");
        cpuLayout->addWidget(m_cpuLabel);
        layout->addWidget(cpuGroup);
        
        // 内存使用率
        QGroupBox *memoryGroup = new QGroupBox("内存");
        QVBoxLayout *memoryLayout = new QVBoxLayout(memoryGroup);
        m_memoryProgress = new QProgressBar();
        m_memoryProgress->setRange(0, 100);
        memoryLayout->addWidget(m_memoryProgress);
        m_memoryLabel = new QLabel("内存: 0% (0 MB / 0 MB)");
        memoryLayout->addWidget(m_memoryLabel);
        layout->addWidget(memoryGroup);
        
        // 磁盘使用率
        QGroupBox *diskGroup = new QGroupBox("磁盘");
        QVBoxLayout *diskLayout = new QVBoxLayout(diskGroup);
        m_diskProgress = new QProgressBar();
        m_diskProgress->setRange(0, 100);
        diskLayout->addWidget(m_diskProgress);
        m_diskLabel = new QLabel("磁盘: 0% (0 MB / 0 MB)");
        diskLayout->addWidget(m_diskLabel);
        layout->addWidget(diskGroup);
        
        layout->addStretch();
        return tab;
    }
    
    void setupTimers() {
        // 进程更新定时器
        m_processTimer = new QTimer(this);
        connect(m_processTimer, &QTimer::timeout, this, &TaskManagerWindow::updateProcesses);
        m_processTimer->start(3000); // 每3秒更新一次
        
        // 系统信息更新定时器
        m_systemTimer = new QTimer(this);
        connect(m_systemTimer, &QTimer::timeout, this, &TaskManagerWindow::updateSystemInfo);
        m_systemTimer->start(2000); // 每2秒更新一次
    }
    
    // UI组件
    QTableWidget *m_processTable;
    QProgressBar *m_cpuProgress;
    QProgressBar *m_memoryProgress;
    QProgressBar *m_diskProgress;
    QLabel *m_cpuLabel;
    QLabel *m_memoryLabel;
    QLabel *m_diskLabel;
    
    // 定时器
    QTimer *m_processTimer;
    QTimer *m_systemTimer;
    
    // 数据管理器
    ProcessManager m_processManager;
    SystemMonitor m_systemMonitor;
    
    // 当前过滤器
    std::string m_currentFilter = "all";
};

#include "task_manager.moc"

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    
    TaskManagerWindow window;
    window.show();
    
    return app.exec();
}